nodejs API

Node.js 是一个基于 Chrome V8 引擎的 JavaScript 运行环境。Node.js 使用了一个事件驱动、非阻塞式 I/O 的模型,使其轻量又高效。Node.js 的包管理器 npm,是全球最大的开源库生态系统。

Node.js Manual & Documentation

Table Of Contents
  • Synopsis 概要
  • Global Objects 全局对象
    • global
    • process
    • require()
    • require.resolve()
    • require.paths
    • __filename
    • __dirname
    • module
  • Timers 定时器
    • setTimeout(callback, delay, [arg], […])
    • clearTimeout(timeoutId)
    • setInterval(callback, delay, [arg], […])
    • clearInterval(intervalId)
  • Modules 模块
    • Core Modules 核心模块
    • File Modules 文件模块
    • Loading from node_modules Folders 从 node_modules 目录中加载
      • Optimizations to the node_modules Lookup Process 优化 node_modules 的查找过程
    • Folders as Modules 目录作为模块
    • Caching 缓存
    • All Together… 总结一下…
    • Loading from the require.paths Folders 从require.paths目录中加载
      • Note: Please Avoid Modifying require.paths 注意:** 请不要修改requires.paths
        • Setting require.paths to some other value does nothing. 将require.paths设为其他值不会产生任何作用
        • Putting relative paths in require.paths is… weird. 不建议在require.paths中发入相对路径
        • Zero Isolation 零隔离
  • Addenda: Package Manager Tips 附录:包管理技巧
  • Addons 扩展插件
  • process 进程

    • Event: ‘exit’ 事件:’exit’
    • Event: ‘uncaughtException’ 事件:’uncaughtException’
    • Signal Events 信号事件
    • process.stdout
    • process.stderr
    • process.stdin
    • process.argv
    • process.execPath
    • process.chdir(directory)
    • process.cwd()
    • process.env
    • process.exit(code=0)
    • process.getgid()
    • process.setgid(id)
    • process.getuid()
    • process.setuid(id)
    • process.version
    • process.installPrefix
    • process.kill(pid, signal=’SIGTERM’)
    • process.pid
    • process.title
    • process.platform
    • process.memoryUsage()
    • process.nextTick(callback)
    • process.umask([mask])
  • util 工具模块

    • util.debug(string)
    • util.log(string)
    • util.inspect(object, showHidden=false, depth=2)
    • util.pump(readableStream, writableStream, [callback])
    • util.inherits(constructor, superConstructor)
  • Events 事件模块
    • events.EventEmitter
      • emitter.addListener(event, listener)
      • emitter.on(event, listener)
      • emitter.once(event, listener)
      • emitter.removeListener(event, listener)
      • emitter.removeAllListeners(event)
      • emitter.setMaxListeners(n)
      • emitter.listeners(event)
      • emitter.emit(event, [arg1], [arg2], […])
      • Event: ‘newListener’ 事件:’newListener’
    • Buffers 缓冲器
      • new Buffer(size)
      • new Buffer(array)
      • new Buffer(str, encoding=’utf8’)
      • buffer.write(string, offset=0, encoding=’utf8’)
      • buffer.toString(encoding, start=0, end=buffer.length)
      • buffer[index]
      • Buffer.isBuffer(obj)
      • Buffer.byteLength(string, encoding=’utf8’)
      • buffer.length
      • buffer.copy(targetBuffer, targetStart=0, sourceStart=0, sourceEnd=buffer.length)
      • buffer.slice(start, end=buffer.length)
  • Streams 流
  • Readable Stream 可读流
    • Event: ‘data’ 事件:’data’
    • Event: ‘end’ 事件:’end’
    • Event: ‘error’ 事件:’error’
    • Event: ‘close’ 事件:’close’
    • Event: ‘fd’ 事件:’fd’
    • stream.readable
    • stream.setEncoding(encoding)
    • stream.pause()
    • stream.resume()
    • stream.destroy()
    • stream.destroySoon()
    • stream.pipe(destination, [options])
  • Writable Stream 可写流
    • Event: ‘drain’ 事件:’drain’
    • Event: ‘error’ 事件:’error’
    • Event: ‘close’ 事件:’close’
    • Event: ‘pipe’ 事件:’pipe’
    • stream.writable
    • stream.write(string, encoding=’utf8’, [fd])
    • stream.write(buffer)
    • stream.end()
    • stream.end(string, encoding)
    • stream.end(buffer)
    • stream.destroy()
  • Crypto 加密模块
    • crypto.createCredentials(details)
    • crypto.createHash(algorithm)
    • hash.update(data)
    • hash.digest(encoding=’binary’)
    • crypto.createHmac(algorithm, key)
    • hmac.update(data)
    • hmac.digest(encoding=’binary’)
    • crypto.createCipher(algorithm, key)
    • cipher.update(data, input_encoding=’binary’, output_encoding=’binary’)
    • cipher.final(output_encoding=’binary’)
    • crypto.createDecipher(algorithm, key)
    • decipher.update(data, input_encoding=’binary’, output_encoding=’binary’)
    • decipher.final(output_encoding=’binary’)
    • crypto.createSign(algorithm)
    • signer.update(data)
    • signer.sign(private_key, output_format=’binary’)
    • crypto.createVerify(algorithm)
    • verifier.update(data)
    • verifier.verify(cert, signature, signature_format=’binary’)
  • TLS (SSL) TLS (SSL)模块
    • s = tls.connect(port, [host], [options], callback)
    • tls.Server
      • tls.createServer(options, secureConnectionListener)
      • Event: ‘secureConnection’ 事件:’secureConnection’
      • server.listen(port, [host], [callback])
      • server.close()
      • server.maxConnections
      • server.connections
  • File System 文件系统模块
    • fs.rename(path1, path2, [callback])
    • fs.renameSync(path1, path2)
    • fs.truncate(fd, len, [callback])
    • fs.truncateSync(fd, len)
    • fs.chmod(path, mode, [callback])
    • fs.chmodSync(path, mode)
    • fs.stat(path, [callback])
    • fs.lstat(path, [callback])
    • fs.fstat(fd, [callback])
    • fs.statSync(path)
    • fs.lstatSync(path)
    • fs.fstatSync(fd)
    • fs.link(srcpath, dstpath, [callback])
    • fs.linkSync(srcpath, dstpath)
    • fs.symlink(linkdata, path, [callback])
    • fs.symlinkSync(linkdata, path)
    • fs.readlink(path, [callback])
    • fs.readlinkSync(path)
    • fs.realpath(path, [callback])
    • fs.realpathSync(path)
    • fs.unlink(path, [callback])
    • fs.unlinkSync(path)
    • fs.rmdir(path, [callback])
    • fs.rmdirSync(path)
    • fs.mkdir(path, mode, [callback])
    • fs.mkdirSync(path, mode)
    • fs.readdir(path, [callback])
    • fs.readdirSync(path)
    • fs.close(fd, [callback])
    • fs.closeSync(fd)
    • fs.open(path, flags, mode=0666, [callback])
    • fs.openSync(path, flags, mode=0666)
    • fs.utimes(path, atime, mtime, callback)
    • fs.utimesSync(path, atime, mtime)
    • fs.futimes(path, atime, mtime, callback)
    • fs.futimesSync(path, atime, mtime)
    • fs.write(fd, buffer, offset, length, position, [callback])
    • fs.writeSync(fd, buffer, offset, length, position)
    • fs.writeSync(fd, str, position, encoding=’utf8’)
    • fs.read(fd, buffer, offset, length, position, [callback])
    • fs.readSync(fd, buffer, offset, length, position)
    • fs.readSync(fd, length, position, encoding)
    • fs.readFile(filename, [encoding], [callback])
    • fs.readFileSync(filename, [encoding])
    • fs.writeFile(filename, data, encoding=’utf8’, [callback])
    • fs.writeFileSync(filename, data, encoding=’utf8’)
    • fs.watchFile(filename, [options], listener)
    • fs.unwatchFile(filename)
  • fs.Stats
  • fs.ReadStream
    • fs.createReadStream(path, [options])
  • fs.WriteStream
    • Event: ‘open’ 事件:’open’
    • fs.createWriteStream(path, [options])
  • Path 路径模块
    • path.normalize(p)
    • path.join([path1], [path2], […])
    • path.resolve([from …], to)
    • path.dirname(p)
    • path.basename(p, [ext])
    • path.extname(p)
    • path.exists(p, [callback])
    • path.existsSync(p)
  • net 网络模块
    • net.createServer([options], [connectionListener])
    • net.createConnection(arguments…)
    • net.Server
      • server.listen(port, [host], [callback])
      • server.listen(path, [callback])
      • server.listenFD(fd)
      • server.close()
      • server.address()
      • server.maxConnections
      • server.connections
      • Event: ‘connection’ 事件:’connection’
      • Event: ‘close’
    • net.Socket
      • new net.Socket([options])
      • socket.connect(port, [host], [callback])
      • socket.connect(path, [callback])
      • socket.bufferSize
      • socket.setEncoding(encoding=null)
      • socket.setSecure()
      • socket.write(data, [encoding], [callback])
      • socket.write(data, [encoding], [fileDescriptor], [callback])
      • socket.end([data], [encoding])
      • socket.destroy()
      • socket.pause()
      • socket.resume()
      • socket.setTimeout(timeout, [callback])
      • socket.setNoDelay(noDelay=true)
      • socket.setKeepAlive(enable=false, [initialDelay])
      • socket.remoteAddress
      • Event: ‘connect’ 事件:’connect’
      • Event: ‘data’ 事件:’data’
      • Event: ‘end’ 事件:’end’
      • Event: ‘timeout’ 事件:’timeout’
      • Event: ‘drain’ 事件:’drain’
      • Event: ‘error’ 事件:’error’
      • Event: ‘close’ 事件:’close’
    • net.isIP
      • net.isIP(input)
      • net.isIPv4(input)
      • net.isIPv6(input)
  • DNS DNS模块
    • dns.lookup(domain, family=null, callback)
    • dns.resolve(domain, rrtype=’A’, callback)
    • dns.resolve4(domain, callback)
    • dns.resolve6(domain, callback)
    • dns.resolveMx(domain, callback)
    • dns.resolveTxt(domain, callback)
    • dns.resolveSrv(domain, callback)
    • dns.reverse(ip, callback)
  • UDP / Datagram Sockets 数据报套接字模块
    • Event: ‘message’ 事件:’message’
    • Event: ‘listening’ 事件:’listening’
    • Event: ‘close’ 事件:’close’
    • dgram.createSocket(type, [callback])
    • dgram.send(buf, offset, length, path, [callback])
    • dgram.send(buf, offset, length, port, address, [callback])
    • dgram.bind(path)
    • dgram.bind(port, [address])
    • dgram.close()
    • dgram.address()
    • dgram.setBroadcast(flag)
    • dgram.setTTL(ttl)
    • dgram.setMulticastTTL(ttl)
    • dgram.setMulticastLoopback(flag)
    • dgram.addMembership(multicastAddress, [multicastInterface])
    • dgram.dropMembership(multicastAddress, [multicastInterface])
  • HTTP HTTP模块
  • http.Server
    • Event: ‘request’ 事件:’request’
    • Event: ‘connection’ 事件:’connection’
    • Event: ‘close’ 事件:’close’
    • Event: ‘request’ 事件:’request’
    • Event: ‘checkContinue’ 事件:’checkContinue’
    • Event: ‘upgrade’ 事件:’upgrade’
    • Event: ‘clientError’ 事件:’clientError’
    • http.createServer(requestListener)
    • server.listen(port, [hostname], [callback])
    • server.listen(path, [callback])
    • server.close()
  • http.ServerRequest
    • Event: ‘data’ 事件:’data’
    • Event: ‘end’ 事件:’end’
    • request.method
    • request.url
    • request.headers
    • request.trailers
    • request.httpVersion
    • request.setEncoding(encoding=null)
    • request.pause()
    • request.resume()
    • request.connection
  • http.ServerResponse
    • response.writeContinue()
    • response.writeHead(statusCode, [reasonPhrase], [headers])
    • response.statusCode
    • response.setHeader(name, value)
    • response.getHeader(name)
    • response.removeHeader(name)
    • response.write(chunk, encoding=’utf8’)
    • response.addTrailers(headers)
    • response.end([data], [encoding])
  • http.request(options, callback)
  • http.get(options, callback)
  • http.Agent
  • http.getAgent(host, port)
    • Event: ‘upgrade’ 事件:’upgrade’
    • Event: ‘continue’ 事件:’continue’
    • agent.maxSockets
    • agent.sockets
    • agent.queue
  • http.ClientRequest
    • Event ‘response’ 事件:’response’
    • request.write(chunk, encoding=’utf8’)
    • request.end([data], [encoding])
    • request.abort()
  • http.ClientResponse
    • Event: ‘data’ 事件:’data’
    • Event: ‘end’ 事件:’end’
    • response.statusCode
    • response.httpVersion
    • response.headers
    • response.trailers
    • response.setEncoding(encoding=null)
    • response.pause()
    • response.resume()
  • https.Server
  • https.createServer
  • https.request(options, callback)
  • https.get(options, callback)
  • URL URL模块
    • url.parse(urlStr, parseQueryString=false)
    • url.format(urlObj)
    • url.resolve(from, to)
  • Query String 查询字符串模块
    • querystring.stringify(obj, sep=’&’, eq=’=’)
    • querystring.parse(str, sep=’&’, eq=’=’)
    • querystring.escape
    • querystring.unescape
  • REPL 交互式解释器
    • repl.start(prompt=’> ‘, stream=process.stdin)
    • REPL Features REPL特性
  • Child Processes 子进程
    • Event: ‘exit’ 事件:’exit’
    • child.stdin
    • child.stdout
    • child.stderr
    • child.pid
    • child_process.spawn(command, args=[], [options])
    • child_process.exec(command, [options], callback)
    • child.kill(signal=’SIGTERM’)
  • Assert 断言模块
    • assert.fail(actual, expected, message, operator)
    • assert.ok(value, [message])
    • assert.equal(actual, expected, [message])
    • assert.notEqual(actual, expected, [message])
    • assert.deepEqual(actual, expected, [message])
    • assert.notDeepEqual(actual, expected, [message])
    • assert.strictEqual(actual, expected, [message])
    • assert.notStrictEqual(actual, expected, [message])
    • assert.throws(block, [error], [message])
    • assert.doesNotThrow(block, [error], [message])
    • assert.ifError(value)
  • TTY 终端模块
    • tty.open(path, args=[])
    • tty.isatty(fd)
    • tty.setRawMode(mode)
    • tty.setWindowSize(fd, row, col)
    • tty.getWindowSize(fd)
  • os Module 操作系统模块
    • os.hostname()
    • os.type()
    • os.release()
    • os.uptime()
    • os.loadavg()
    • os.totalmem()
    • os.freemem()
    • os.cpus()
  • Debugger 调试器
    • Advanced Usage 高级用法
  • Appendixes 附录
    • Appendix 1 - Third Party Modules 附录 1 - 第三方模块

Synopsis 概要

An example of a web server written with Node which responds with ‘HelloWorld’:下边是一个用Node编写的对所有请求简单返回’Hello World‘的web服务器例子:

var http = require('http');

http.createServer(function (request, response) {
  response.writeHead(200, {'Content-Type': 'text/plain'});
  response.end('Hello World\n');
}).listen(8124);

console.log('Server running at http://127.0.0.1:8124/');

To run the server, put the code into a file called example.js and executeit with the node program
要运行这个服务器程序,只要将上述代码保存为文件example.js并用node程序执行此文件:

> node example.js
Server running at http://127.0.0.1:8124/

All of the examples in the documentation can be run similarly.
此文档中所有例子均可用同样的方法运行。## Global Objects 全局对象
These object are available in the global scope and can be accessed from anywhere.
这些对象在全局范围内均可用,你可以在任何位置访问这些对象。

global

The global namespace object.
全局命名空间对象
In browsers, the top-level scope is the global scope. That means that inbrowsers if you’re in the global scopevar something will define a globalvariable. In Node this is different. The top-level scope is not the globalscope;var something inside a Node module will be local to that module.
在浏览器中,顶级作用域为全局作用域,在全局作用域下通过var something即定义了一个全局变量。但是在Node中并不如此,顶级作用域并非是全局作用域,在Node模块中通过var something定义的变量仅作用于该模块。

process

The process object. See the ‘process object’ section.
进程对象,参见’process object’章节。

require()

To require modules. See the ‘Modules’ section.
加载模块,参见’Modules’章节。

require.resolve()

Use the internal require() machinery to look up the location of a module,but rather than loading the module, just return the resolved filename.
使用内部函数require()的机制查找一个模块的位置,而不用加载模块,只是返回解析后的文件名。

require.paths

An array of search paths for require(). This array can be modified to addcustom paths.
require()的搜索路径数组,你可以修改该数组添加自定义的搜索路径。
Example: add a new path to the beginning of the search list
例如:将一个新的搜索路径插入到搜索列表的头部。

require.paths.unshift('/usr/local/node');
__filename

The filename of the script being executed. This is the absolute path, and not necessarilythe same filename passed in as a command line argument.
当前正在执行的脚本的文件名。这是一个绝对路径,可能会和命令行参数中传入的文件名不同。
Example: running node example.js from /Users/mjr
例如:在目录/Users/mjr下运行node example.js

console.log(__filename);
// /Users/mjr/example.js
__dirname

The dirname of the script being executed.
当前正在执行脚本所在的目录名。
Example: running node example.js from /Users/mjr
例如:在目录/Users/mjr下运行node example.js

console.log(__dirname);
// /Users/mjr
module

A reference to the current module. In particularmodule.exports is the same as theexports object. Seesrc/Node.jsfor more information.
指向当前模块的引用。特别的,当你通过module.exports和exports两种方式访问的将是同一个对象,参见src/Node.js。


Timers 定时器
setTimeout(callback, delay, [arg], […])

To schedule execution of callback after delay milliseconds. Returns atimeoutId for possible use withclearTimeout(). Optionally, you canalso pass arguments to the callback.
设定一个delay毫秒后执行callback回调函数的计划。返回值timeoutId可被用于clearTimeout()。可以设定要传递给回调函数的参数。

clearTimeout(timeoutId)

Prevents a timeout from triggering.
清除定时器,阻止指定的timeout(超时)定时器被触发。

setInterval(callback, delay, [arg], […])

To schedule the repeated execution of callback every delay milliseconds.Returns aintervalId for possible use with clearInterval(). Optionally,you can also pass arguments to the callback.
设定一个每delay毫秒重复执行callback回调函数的计划。返回值intervalId可被用于clearInterval()。可以设定要传递给回调函数的参数。

clearInterval(intervalId)

Stops a interval from triggering.
清除定时器,阻止指定的interval(间隔)定时器被触发。## Modules 模块
Node uses the CommonJS module system.Node has a simple module loading system. In Node, files and modules are inone-to-one correspondence. As an example,foo.js loads the modulecircle.js in the same directory.
Node使用CommonJS模块系统。Node有一个简单的模块装载系统,在Node中,文件和模块是一一对应的。下面的例子展示了foo.js文件如何在相同的目录中加载circle.js模块。
The contents of foo.js:
foo.js的内容为:

var circle = require('./circle.js');
console.log( 'The area of a circle of radius 4 is '
           + circle.area(4));

The contents of circle.js:
circle.js的内容为:

var PI = Math.PI;

exports.area = function (r) {
  return PI * r * r;
};

exports.circumference = function (r) {
  return 2 * PI * r;
};

The module circle.js has exported the functions area() andcircumference(). To export an object, add to the specialexportsobject.
circle.js模块输出了area()和circumference()两个函数,为了以对象的形式输出,需将要输出的函数加入到一个特殊的exports对像中。
Variableslocal to the module will be private. In this example the variable PI isprivate to circle.js.
模块的本地变量是私有的。在上面的例子中,变量PI就是circle.js私有的。

Core Modules 核心模块

Node has several modules compiled into the binary. These modules aredescribed in greater detail elsewhere in this documentation.
Node有一些编译成二进制的模块。这些模块在这篇文档的其他地方有详细描述。
The core modules are defined in node’s source in the lib/ folder.
核心模块在node源代码中的lib文件夹下。
Core modules are always preferentially loaded if their identifier ispassed to require(). For instance, require(‘http’) will alwaysreturn the built in HTTP module, even if there is a file by that name.
核心模块总是被优先加载,如果它们的标识符被require()调用。例如,require(‘http’)将总是返回内建的HTTP模块,即便又一个同名文件存在。

File Modules 文件模块

If the exact filename is not found, then node will attempt to load therequired filename with the added extension of.js, and then .node..js files are interpreted as JavaScript text files, and.node filesare interpreted as compiled addon modules loaded with dlopen.
如果没有找到确切的文件名,node将尝试以追加扩展名.js后的文件名读取文件,如果还是没有找到则尝试追加扩展名.node。.js文件被解释为JavaScript格式的纯文本文件,.node文件被解释为编译后的addon(插件)模块,并使用dlopen来加载。
A module prefixed with ‘/‘ is an absolute path to the file. Forexample,require(‘/home/marco/foo.js’) will load the file at/home/marco/foo.js.
以’/‘为前缀的模块是一个指向文件的绝对路径,例如require(‘/home/marco/foo.js’)将加载文件/home/marco/foo.js。
A module prefixed with ‘./‘ is relative to the file calling require().That is, circle.js must be in the same directory asfoo.js forrequire(‘./circle’) to find it.
以’./‘为前缀的模块是指向文件的相对路径,相对于调用require()的文件。也就是说为了使require(‘./circle’)能找到正确的文件,circle.js必须位于与foo.js 相同的路径之下。
Without a leading ‘/‘ or ‘./‘ to indicate a file, the module is either a”core module” or is loaded from anode_modulesfolder.
如果标明一个文件时没有 ‘/‘ 或 ‘./‘前缀,该模块或是”核心模块”,或者位于 node_modules目录中。

Loading from node_modules Folders 从 node_modules 目录中加载

If the module identifier passed to require() is not a native module,and does not begin with’/‘, ‘../‘, or ‘./‘, then node starts at theparent directory of the current module, and adds/node_modules, andattempts to load the module from that location.
如果传递到 require()的模块标识符不是一个核心模块,并且不是以’/‘,’../‘或’./‘开头,node将从当前模块的父目录开始,在其/node_modules子目录中加载该模块。
If it is not found there, then it moves to the parent directory, and soon, until either the module is found, or the root of the tree isreached.
如果在那里没有找到,就转移到上一级目录,依此类推,直到找到该模块或到达目录树的根结点。
For example, if the file at ‘/home/ry/projects/foo.js’ calledrequire(‘bar.js’), then node would look in the following locations, inthis order:
例如,如果在文件 ‘/home/ry/projects/foo.js’中调用 `require(‘bar.js’),node将会依次查找以下位置:
/home/ry/projects/node_modules/bar.js
/home/ry/node_modules/bar.js
/home/node_modules/bar.js
/node_modules/bar.js
This allows programs to localize their dependencies, so that they do notclash.
这允许程序本地化他们的依赖关系,避免发生冲突。

Optimizations to the node_modules Lookup Process 优化 node_modules 的查找过程

When there are many levels of nested dependencies, it is possible forthese file trees to get fairly long. The following optimizations are thusmade to the process.
如果有很多级的嵌套信赖,文件树会变得相当的长,下面是对这一过程的一些优化。
First, /node_modules is never appended to a folder already ending in/node_modules.
首先, /node_modules不要添加到以 /node_modules结尾的目录上。
Second, if the file calling require() is already inside a node_moduleshierarchy, then the top-mostnode_modulesfolder is treated as theroot of the search tree.
其次,如果调用require()的文件已经位于一个node_modules层次中,最上级的node_modules目录将被作为搜索的根。
For example, if the file at’/home/ry/projects/foo/node_modules/bar/node_modules/baz/quux.js’calledrequire(‘asdf.js’), then node would search the followinglocations:
例如,如果文件’/home/ry/projects/foo/node_modules/bar/node_modules/baz/quux.js’调用require(‘asdf.js’),node会在下面的位置进行搜索:
/home/ry/projects/foo/node_modules/bar/node_modules/baz/node_modules/asdf.js
/home/ry/projects/foo/node_modules/bar/node_modules/asdf.js
/home/ry/projects/foo/node_modules/asdf.js

Folders as Modules 目录作为模块

It is convenient to organize programs and libraries into self-containeddirectories, and then provide a single entry point to that library.There are three ways in which a folder may be passed torequire() asan argument.
很方便将程序或库组织成自包含的目录,并提供一个单独的入口指向那个库。有三种方式可以将一个子目录作为参数传递给 require() 。
The first is to create a package.json file in the root of the folder,which specifies amain module. An example package.json file mightlook like this:
第一种方法是在目录的根下创建一个名为package.json的文件,它指定了一个main 模块。一个package.jso文件的例子如下面所示:

{ "name" : "some-library",
  "main" : "./lib/some-library.js" }

If this was in a folder at ./some-library, thenrequire(‘./some-library’) would attempt to load./some-library/lib/some-library.js.
如果此文件位于./some-library目录中,require(‘./some-library’)将试图加载文件./some-library/lib/some-library.js。
This is the extent of Node’s awareness of package.json files.
这是Node感知package.json文件的范围。
If there is no package.json file present in the directory, then nodewill attempt to load anindex.js or index.node file out of thatdirectory. For example, if there was no package.json file in the aboveexample, thenrequire(‘./some-library’) would attempt to load:
如果在目录中没有package.json文件,node将试图在该目录中加载index.js 或 index.node文件。例如,在上面的例子中没有 package.json文件,require(‘./some-library’)将试图加载:
./some-library/index.js
./some-library/index.node

Caching 缓存

Modules are cached after the first time they are loaded. This means(among other things) that every call torequire(‘foo’) will getexactly the same object returned, if it would resolve to the same file.
模块在第一次加载后将被缓存。这意味着(类似其他缓存)每次调用require(‘foo’)如果解析到相同的文件,那么将返回同一个对象。

All Together… 总结一下…

To get the exact filename that will be loaded when require() is called, usetherequire.resolve() function.
可使用require.resolve()函数,获得调用require()时将加载的准确的文件名。
Putting together all of the above, here is the high-level algorithmin pseudocode of what require.resolve does:
综上所述,这里以伪代码的形式给出require.resolve的算法逻辑:

require(X)
1. If X is a core module,
   a. return the core module
   b. STOP
2. If X begins with `./` or `/`,
   a. LOAD_AS_FILE(Y + X)
   b. LOAD_AS_DIRECTORY(Y + X)
3. LOAD_NODE_MODULES(X, dirname(Y))
4. THROW "not found"

LOAD_AS_FILE(X)
1. If X is a file, load X as JavaScript text.  STOP
2. If X.js is a file, load X.js as JavaScript text.  STOP
3. If X.node is a file, load X.node as binary addon.  STOP

LOAD_AS_DIRECTORY(X)
1. If X/package.json is a file,
   a. Parse X/package.json, and look for "main" field.
   b. let M = X + (json main field)
   c. LOAD_AS_FILE(M)
2. LOAD_AS_FILE(X/index)

LOAD_NODE_MODULES(X, START)
1. let DIRS=NODE_MODULES_PATHS(START)
2. for each DIR in DIRS:
   a. LOAD_AS_FILE(DIR/X)
   b. LOAD_AS_DIRECTORY(DIR/X)

NODE_MODULES_PATHS(START)
1. let PARTS = path split(START)
2. let ROOT = index of first instance of "node_modules" in PARTS, or 0
3. let I = count of PARTS - 1
4. let DIRS = []
5. while I > ROOT,
   a. if PARTS[I] = "node_modules" CONTINUE
   c. DIR = path join(PARTS[0 .. I] + "node_modules")
   b. DIRS = DIRS + DIR
6. return DIRS
很惭愧<br><br>只做了一点微小的工作<br>谢谢大家